package io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.text.Document;

import main.LineNumberUpdater;

/**
 * Class to inport data from file
 * @author Balazs Pete
 *
 */
public class In extends Thread{
	File file = null;
	FileReader reader = null;
	Document doc = null;
	
	/**
	 * Create and configure saving conditions
	 * @param path path to file (excl file name)
	 * @param fileName file name (excl extension and dot)
	 * @param extension file extension (excl the dot in front)
	 * @author Balazs Pete
	 */
	public In(){
		JFileChooser ch = new JFileChooser();
		if(ch.showDialog(null, "Open") == JFileChooser.APPROVE_OPTION) {
			file = ch.getSelectedFile();
		}
	}
	
	/**
	 * Save current text area to file
	 * @author Balazs Pete
	 */
	public void run(){
		char[] ch = new char[100000];
		int n = 0;
		
		try {
		    Reader in = new BufferedReader(new InputStreamReader(
		        new FileInputStream(file), "UTF-8"));
		    n = in.read(ch);
		    in.close();
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
			new errors.NoSuchFile();
		}
		
		int i=0;
		while(i<n){
			String s = ch[i]+"";
			main.MainWindow.insertText(s,false);
			i++;
		}
		main.MainWindow.updateText();
		
		LineNumberUpdater update = new LineNumberUpdater(main.MainWindow.getLineNumber());
		update.start();
		
		JOptionPane.showMessageDialog(null, "Import complete");
		
		main.MainWindow.runColoring();
	}
	
}
